<?php

namespace app\common\model;

use app\common\model\search\PushMessageSearch;
use \think\Paginator;

class PushMessage extends BaseModel
{
    use PushMessageSearch;

    protected $name = "push_message";

    /**
     * 获取数据列表
     * @param array $where 条件
     * @param string $field 字段
     * @return Paginator
     */
    public function getLists(array $where, string $field="*"): Paginator
    {
        return $this->mongoSearch()
                    ->field($field)
                    ->where($where)
                    ->order('created_at', 'desc')
                    ->paginate($this->pageLimit);
    }

    /**
     * 添加数据
     * @param array $param
     * @return string
     */
    public function addData(array $param): string
    {
        //添加时销毁自带的主键id
        unset($param['id']);
        return $this->save($param);
    }

    /**
     * 更新数据
     * @param array $param
     * @return bool
     */
    public function saveData($id, array $param): bool
    {
        $model = self::find($id);
        return $model->save($param);
    }

    /**
     * 删除
     * @param array $id
     * @return bool
     */
    public function delData(array $id): bool
    {
        return self::destroy($id);
    }

    /**
     * 数据合计
     * @param array $where 条件
     * @retrun int
     */
    public function getCount(array $where): int
    {
        return $this->mongoSearch()->where($where)->count();
    }

    /**
     * 获取指定字段
     * @param array $where 条件
     * @param string $field 返回字段
     * @retrun array
     */
    public function getColumn(array $where, string $field): array
    {
        return $this->mongoSearch()->where($where)->column($field);
    }

    /**
     * 获取患者端数据
     * @param string $patientId 患者id
     * @return Paginator
     */
    public function getPatientDatas(string $patientId): Paginator
    {
        $field = 'id,type,typeName,projectId,projectName,ed_id,ed_name,content,created_at,follow_id,history_id,isview';
        return $this->mongoSearch()
                    ->where('patientId', $patientId)
                    ->field($field)
                    ->order('created_at', 'desc')
                    ->paginate($this->pageLimit)
                    ->each(function($item, $key){
                        if (empty($item['typeName'])) {
                            if ($item['type'] == 1){
                                $item['typeName'] = '随访';
                            } else if($item['type'] == 2) {
                                $item['typeName'] = '宣教';
                            }
                        }
                        return $item;
                    });
    }

    /**
     * 获取工作台随访消息
     * @param int $creator_id
     * @return array
     */
    public function getFollowMessge(int $creator_id): array
    {
        $where['type'] = 1;
        $where['creator_id'] = $creator_id;
        return $this->where($where)->order('created_at', 'desc')->select()->toArray();
    }
}